/**
 *  Copyright 2011 Pavlov Dm.
 *  Licensed under the MIT License
 */

package org.motiv.config;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
 * Cache configuration parser class.
 * @author Pavlov Dm
 */
public class CacheConfigurationParser{
	
	private Node cacheNode;
	
	public CacheConfigurationParser(Node cacheNode){
		if(cacheNode!=null){
			this.cacheNode = cacheNode;
		} else {
			throw new IllegalArgumentException("Cache node is null");
		}
	}
	/**
	* Parse cache configuration method
	*/
	public CacheConfiguration parseCache(){
			
		CacheConfiguration cacheConfiguration;
		
		Element cacheElement = (Element) cacheNode;
		
		String sName = isAttributeSet(cacheElement,"name");
		if(sName == null){
			return null;
		}
		int iMaxElementsInMemory = strToInt(isAttributeSet(cacheElement,"maxElementsInMemory"),0);
		
		cacheConfiguration = new CacheConfiguration(sName,iMaxElementsInMemory);
		//Set cache eternal, by default true
		cacheConfiguration.setEternal(strToBool(isAttributeSet(cacheElement,"eternal"),true));
		//Set cache elements Time To Idle, by default 0
		cacheConfiguration.setTimeToIdleSeconds(strToLong(isAttributeSet(cacheElement,"timeToIdleSeconds"),0L));
		//Set cache elements Time To Live, by default 0
		cacheConfiguration.setTimeToLiveSeconds(strToLong(isAttributeSet(cacheElement,"timeToLiveSeconds"),0L));
		//Set cache Overflow To Disk, by default false
		cacheConfiguration.setOverflowToDisk(strToBool(isAttributeSet(cacheElement,"overflowToDisk"),false));
		//Set cache Max Elements On Disk, by default 0
		cacheConfiguration.setMaxElementsOnDisk(strToInt(isAttributeSet(cacheElement,"maxElementsOnDisk"),0));
		//Set cache Disk Spool Buffer Size
		cacheConfiguration.setDiskSpoolBufferSizeMB(strToInt(isAttributeSet(cacheElement,"diskSpoolBufferSizeMB"),-1));
		//Set cache Eviction Policy 
		cacheConfiguration.setMemoryStoreEvictionPolicy(isAttributeSet(cacheElement,"memoryStoreEvictionPolicy"));
		
		
		return cacheConfiguration;
	}
	private String isAttributeSet(Element cacheElement,String sArrtName){
		String sValue = cacheElement.getAttribute(sArrtName);
		return sValue == null || sValue.isEmpty() ? null : sValue;
	}
	/**
	* Convert string to int method
	*/
	private int strToInt(String sValue,int defaultValue){
		try {
			return sValue == null ? defaultValue : Integer.parseInt(sValue);
		} catch(NumberFormatException ex) {
			return defaultValue;
		} 
	}
	/**
	* Convert string to long method
	*/
	private long strToLong(String sValue,long defaultValue){
		try {
			return sValue == null ? defaultValue : Long.parseLong(sValue);
		} catch(NumberFormatException ex) {
			return defaultValue;
		} 
	}
	/**
	* Convert string to boolean method
	*/
	private boolean strToBool(String sValue,boolean defaultValue){
		try {
			return sValue == null ? defaultValue : Boolean.parseBoolean(sValue);
		} catch(NumberFormatException ex) {
			return defaultValue;
		} 
	}
}
